<template>
  <div class="card">
    <div class="title2 title2-padding">遥控指令</div>
    <el-row>
      <el-col :span="12">
        <div class="custom-scrollbar" :style="{ maxHeight: autoHeight }">
          <el-tree
              ref="tlcTreeRef"
              class="tel-tree"
              :data="treeData"
              show-checkbox
              :default-expand-all="false"
              node-key="id"
              highlight-current
              :expand-on-click-node="false"
              @check="handelChange">
            <template #default="{ node, data }">
              <span>{{ data.label }}</span>
            </template>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="12">
        <div v-show="dialogVisible">
          <CmdsPanel class="cmd-div card" @close="dialogVisible = false"></CmdsPanel>
        </div>
      </el-col>
    </el-row>
  </div>
  <div class="card">
    <TcLogs></TcLogs>
  </div>
</template>

<script setup>
import { ref, onBeforeMount  } from 'vue'
import { fetchTcList } from '@/api/loads-api.js'
import { useTcStore } from '@/stores/tc-module.js'
import CmdsPanel from './CmdsPanel.vue'
import TcLogs from './TcLogs.vue'


const tcStore = useTcStore()
const emit = defineEmits(['check'])
const tlcTreeRef = ref(null)
let dialogVisible = ref(false)
let treeData = ref([])
let autoHeight = ref('300px')

onBeforeMount(() => {
  const HeightX = 0.55
  autoHeight.value = `${ Math.ceil(window.innerHeight * HeightX) }px`
})
fetchTcList ({}, (response) => {
  const resData = response.data.data
  const allTcls = resData.cmdSheet || {}

  for ( const cmdItem of allTcls )   {
    let children = []
    for(let row of cmdItem.cmds){
      let child = { id: row.id, label: ` ${row.cmdName}` }
      children.push(child)
      tcStore.assingCmd(row)
    }
    treeData.value.push({
      id: 0,
      label: cmdItem['name'],
      children: children
    })
  }
}, (err)=> {
  console.log("获取遥控命令列表失败:", err)
})

const handelChange = () => {
  const nodes = tlcTreeRef.value.getCheckedKeys()
  // console.log("nodes:", nodes)
  // if(nodes[0] === 0) {
  //   nodes.splice(0, 1)
  // }
  tcStore.setSelectNode(nodes)
  if(nodes.length > 0) {
    dialogVisible.value = true
  } else {
    dialogVisible.value = false
  }
}

const closePanel = () => {
  dialogVisible.value = false
  tlcTreeRef.value.setCheckedKeys([], false)
  tcStore.setSelectNode([])
}
</script>

<style lang="scss" scoped>
.tlcmd-div .cmd-div {
  //margin-left: 20px;
}
</style>